package com.itheima.health.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.common.CustomException;
import com.itheima.health.constant.MessageConstant;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.mapper.CheckItemMapper;
import com.itheima.health.pojo.CheckItem;
import com.itheima.health.service.CheckItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 *  检查项服务层实现
 */
@Service
public class CheckItemServiceImpl implements CheckItemService {
    @Autowired
    private CheckItemMapper checkItemMapper;

    @Override
    public Boolean add(CheckItem checkItem) {
        int i = checkItemMapper.add(checkItem);
        if (i > 0) {
            return true;
        }
        return false;
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //1.设置分页信息  这个方法由两个参数  第一个参数是当前页  第二个参数是显示每页显示多少条
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        //2.调用mapper查询
        Page<CheckItem> page = checkItemMapper.findPage(queryPageBean.getQueryString());
        //3.封装到PageResult中并返回
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public Boolean delete(Integer id) {
        //1.根据检查项id查询检查组数，用于判断是否有检查组关联检查项
        long count = checkItemMapper.findCountByCheckItemId(id);
        if (count > 0) {
            //2.如果有关联检查组，抛出异常
            throw new CustomException("当前检查项被引用，不能删除");
        }
        int i = checkItemMapper.delete(id);
        if (i > 0) {
            return true;
        }
        return false;
    }

    @Override
    public CheckItem findById(Integer id) {
        return checkItemMapper.selectById(id);
    }

    @Override
    public Boolean edit(CheckItem checkItem) {
        int i = checkItemMapper.edit(checkItem);
        if (i > 0){
            return true;
        }
        return false;
    }

    @Override
    public List<CheckItem> findAll() {
        return checkItemMapper.findAll();
    }

    @Override
    public Integer[] findCheckItemIdsByCheckGroupId(Integer id) {
        return checkItemMapper.findCheckItemIdsByCheckGroupId(id);
    }

}
